<template>
  <canvas id="canvas" width="50" height="30"></canvas>
</template>
<script>
import Socket from "@/utils/Socket";
import NMPrintSocket from "@/utils/Print";
export default {
  name: "print",
  props: {
    imgList: Array,
  },
  data() {
    const jsonObj = {
      printerImageProcessingInfo: {
        printQuantity: 1,
      },
    };
    return {
      // 打印服务是否连接成功
      printSocketOpen: false,
      nMPrintSocket: null,
      usbPrinters: {},
      usbSelectPrinter: "",
      // 打印浓度
      density: 3,
      jsonObj,
      // 纸张类型
      label_type: 1,
      print_mode: 2,
      canvas: undefined,
      ctx: undefined,
      imgPrintData: [],
    };
  },
  mounted() {
    // 创建socket实例
    const socketData = new Socket("ws://127.0.0.1:37989");

    socketData.open(
      (openBool) => {
        
        console.log(openBool, "openBool");
        this.printSocketOpen = openBool;
        this.init();
        this.getPrinters();
      },
      (msg) => {
        if (msg.resultAck.callback != undefined) {
          const callbackName = msg.resultAck.callback.name;
          const msgInfo = msg.resultAck.info;
          if (callbackName == "onCoverStatusChange") {
            //盒盖状态：0-闭合、1-打开
            console.log("盒盖状态", msgInfo.capStatus);
          } else if (callbackName == "onElectricityChange") {
            //"power" : 0-4, // 电池电量等级（共5档）
            console.log("电池电量等级", msgInfo.power);
          }
        }
      }
    );
    // 创建打印实例
    this.nMPrintSocket = new NMPrintSocket(socketData);
  },
  methods: {
    handlePrint() {
      if (!this.printSocketOpen) return this.$message.warning("打印服务未开启");
      this.$message.success("正在打印中...");
      const promiseList = [];
      for (let i of this.imgList) {
        promiseList.push(this.loadImg(i));
      }
      Promise.all(promiseList).then((arr) => {
        this.batchPrintJob(this.imgPrintData);
      });
    },
    base64Process(data) {
      //去除base64的数据头
      return data.substring(22);
    },
    //初始化SDK
    async init() {
      console.log('init');
      if (!this.printSocketOpen) return this.$message.warning("打印服务未开启");
      //初始化数据
      try {
        const res = await this.nMPrintSocket.initSdk({ fontDir: "" });
        if (res.resultAck.errorCode == 0) {
          console.log("初始化成功");
          this.initBool = true;
        } else {
          console.log("初始化失败");
          this.initBool = false;
        }
      } catch (err) {
        console.error(err);
      }
    },
    loadImg(imgUrl) {
      return new Promise((resolve, reject) => {
        fetch(imgUrl, { mode: "cors" })
          .then((res) => {
            return res.blob();
          })
          .then((blob) => {
            return new Promise((resolve, reject) => {
              const reader = new FileReader();
              reader.onload = () => resolve(reader.result);
              reader.onerror = (error) => reject(error);
              reader.readAsDataURL(blob);
            });
          })
          .then((base64) => {
            this.imgPrintData.push({
              InitDrawingBoardParam: {
                width: 50,
                height: 30,
                rotate: 0,
                path: "ZT001.ttf",
                verticalShift: 0,
                HorizontalShift: 0,
              },
              elements: [
                {
                  type: "image",
                  json: {
                    x: 0,
                    y: 0,
                    height: 30,
                    width: 50,
                    rotate: 0,
                    imageProcessingType: 0,
                    imageProcessingValue: 127,
                    imageData: this.base64Process(base64),
                  },
                },
              ],
            });
            resolve();
          })
          .catch((err) => {
            this.$message.error("打印失败", err);
            this.$emit('print-success')
            reject("打印失败", err);
          });
      });
    },
    //更新打印机列表
    async getPrinters() {
      if (!this.printSocketOpen) {
        return this.$message.warning("打印服务未开启");
      }
      console.log("开始获取打印机");
      try {
        const allPrintersRes = await this.nMPrintSocket.getAllPrinters();
        console.log(allPrintersRes, "allPrintersRes");
        if (allPrintersRes.resultAck.errorCode === 0) {
          const allPrinters = JSON.parse(allPrintersRes.resultAck.info);
          this.usbPrinters = { ...allPrinters };
          this.usbSelectPrinter = Object.keys(this.usbPrinters)[0];
          console.log("printers", this.usbPrinters);
          this.selectOnLineUsbPrinter();
        } else {
          this.$message.warning("没有在线的打印机");
          this.$emit('print-success')
          
        }
      } catch (err) {
        console.error(err);
      }
    },
    // 连接打印机
    async selectOnLineUsbPrinter() {
      if (!this.printSocketOpen) {
        return this.$message.warning("打印服务未开启");
      }
      console.log("开始连接打印机");
      try {
        const res = await this.nMPrintSocket.selectPrinter(
          this.usbSelectPrinter,
          parseInt(this.usbPrinters[this.usbSelectPrinter])
        );
        console.log("选择打印机", res);

        if (res.resultAck.errorCode === 0) {
          console.log("连接成功");
          this.onlineUsbBool = true;
        } else {
          console.log("连接失败");
          this.onlineUsbBool = false;
          this.$message.warning("连接失败");
          this.$emit('print-success')
        }
      } catch (err) {
        this.$emit('print-success')

        console.error(err);
      }
    },
    // 批量打印
    async batchPrintJob(list) {
      console.log("list", list);
      try {
        const startRes = await this.nMPrintSocket.startJob(
          this.density,
          this.label_type,
          this.print_mode,
          list.length
        );
        console.log(1222, startRes);
        if (startRes.resultAck.errorCode == 0) {
          // 提交打印任务
          await this.printTag(list, 0);
        }
      } catch (err) {
        console.error(err);
      }
    },
    // 绘制打印标签
    async printTag(list, x) {
      console.log(2, list);
      //设置画布尺寸
      try {
        const res = await this.nMPrintSocket.InitDrawingBoard(
          list[x].InitDrawingBoardParam
        );
        if (res.resultAck.errorCode != 0) {
          return;
        }
        // 提交打印任务
        this.printItem(list, x, list[x].elements, 0);
      } catch (err) {
        console.error(err);
      }
    },
    async printItem(list, x, item, i) {
      try {
        if (i < item.length) {
          let arrParse;
          arrParse = await this.nMPrintSocket.DrawLableImage(item[i].json);
          if (arrParse.resultAck.errorCode != 0) {
            return;
          }
          i++;
          await this.printItem(list, x, item, i);
        } else {
          const commitRes = await this.nMPrintSocket.commitJob(
            null,
            JSON.stringify(this.jsonObj)
          );
          if (
            commitRes.resultAck.printQuantity == list.length &&
            commitRes.resultAck.onPrintPageCompleted ==
              this.jsonObj.printerImageProcessingInfo.printQuantity
          ) {
            //结束打印任务
            const endRes = await this.nMPrintSocket.endJob();
            if (endRes.resultAck.errorCode === 0) {
              this.imgPrintData = [];
              this.$emit('print-success')
              this.$message.success("打印完成");
            }
            return;
          }
          //回调为提交成功，同时数据未发送完成时，可继续提交数据
          if (commitRes.resultAck.errorCode === 0 && x < list.length - 1) {
            //数据提交成功，数据下标+1
            console.log("发送下一页打印数据： ");
            x++;
            await this.printTag(list, x);
          }
        }
      } catch (err) {
        console.error(err);
        this.$emit('print-success')
      }
    },
  },
};
</script>
